<template>
  <div class="image-upload"  :class="{ disabled: isDisabled }">
    <el-upload
      class="UPL"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :http-request="httpRequest"
      :on-change="onChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-dialog
      title="图片预览"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>


<script>
// var COS = require('cos-js-sdk-v5')

import cos from "@/utils/cos";

// SecretId: AKIDSvIzTkmZ6Y2NUMxVx95nMipibLwLhspZ
// SecretKey: f6YotujM5e4jTAgaKrFPNGxQhmdDaw87
export default {
  name: "ImageUpload",
  props: {
    limit: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  computed: {
    isDisabled() {
      return this.fileList.length >= this.limit;
    },
    isAllStatusSuccess() {
      return this.fileList.every((item) => item.status === "success");
    },
  },
  methods: {
    //上传前的校验对文件大小和文件类型进行限制
    beforeUpload(file) {
      // 1. 限制文件类型 file.type
      const types = ["image/jpeg", "image/gif", "image/bmp", "image/png"];
      if (!types.includes(file.type)) {
        this.$message.error("上传的图片格式, 必须是jpg, gif, bmp, png的格式!");
        return false;
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error("上传头像过大, 超过了5M, 必须5M以内");
        return false;
      }
    },
    onChange(file, fileList) {
      this.fileList = [...fileList];
    },

    httpRequest({ file }) {
      
      const ulFile = this.fileList.find((item) => item.uid === file.uid);
      ulFile.status = "uploading";
      if (!file) return;
      cos.putObject(
        {
          Bucket: "renzi-1316190625",
          Region: "ap-beijing",
          Key: +new Date() + file.name,
          Body: file,
          onProgress: function (progressData) {
            ulFile.percentage = progressData.percent * 100;
          },
        },
        function (err, data) {
          if (err) {
            this.$message.error("上传失败，请稍后重试");
            return;
          }
          ulFile.url = "//" + data.Location;
          setTimeout(() => {
            ulFile.status = "success";
          }, 500);
        }
      );
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onExceed() {
      this.$message.warning("已经达到最大上传张数");
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid);
    },
  },
};
</script>

<style scoped lang="scss">
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}

</style>